package com.jams.goodox.update;

import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.IBinder;

import com.jams.goodox.BuildConfig;
import com.jams.goodox.TownApplicationLike;
import com.jams.goodox.utils.FileUtil;

import java.io.File;

public class UpdateService extends Service {
    /**
     * 安卓系统下载类
     **/
    DownloadManager manager;

    /**
     * 接收下载完的广播
     **/
    DownloadCompleteReceiver receiver;

    /**
     * 初始化下载器
     **/
    private void initDownManager() {
        try {
            manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

            receiver = new DownloadCompleteReceiver();

            //设置下载地址
            DownloadManager.Request down = new DownloadManager.Request(
                    Uri.parse(UpDateVersionUtils.Apk_Update_Url));

            // 设置允许使用的网络类型，这里是移动网络和wifi都可以
            down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
                    | DownloadManager.Request.NETWORK_WIFI);

            // 下载时，通知栏显示途中
            down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
            down.setTitle(BuildConfig.APP_NAME);
            down.setDescription("发现新版本，请求下载中...");

            // 显示下载界面
            down.setVisibleInDownloadsUi(true);
            // 设置下载后文件存放的位置
            down.setDestinationInExternalPublicDir(FileUtil.FILE_DIR + File.separator + "apk",
                    UpDateVersionUtils.Download_Apk_Name);

//        down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);//下载成功通知停留
            // 将下载请求放入队列
            manager.enqueue(down);
            TownApplicationLike.IsDownLoadingApk = true;
            //注册下载广播
            registerReceiver(receiver, new IntentFilter(
                    DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        } catch (Exception e) {
            TownApplicationLike.IsDownLoadingApk = false;
            stopSelf();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        // 调用下载
        initDownManager();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        // 注销下载广播
        if (receiver != null)
            unregisterReceiver(receiver);

        super.onDestroy();
    }

    // 接受下载完成后的intent
    class DownloadCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            //判断是否下载完成的广播
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                TownApplicationLike.IsDownLoadingApk = false;
                UpDateVersionUtils.installApk(context);
                //停止服务并关闭广播
                stopSelf();
            }
        }
    }
}
